<?php defined('SYSPATH') OR die('No direct access allowed.');

class Number_Plugin extends WB_FormItem {
	
	protected $decimals, $dec_point, $thousands_sep, $min, $max;
	
	public function __construct($name='', $params=array())
	{
		parent::__construct($name, $params, 'text number integer');
		
		//TODO: limiting decimals in JavaScript
		$this->decimals = isset($this->params['decimals']) ? $this->params['decimals'] : 0;		//only affects table view
		$this->dec_point = isset($this->params['dec_point']) ? $this->params['dec_point'] : '.';
		$this->thousands_sep = isset($this->params['thousands_sep']) ? $this->params['thousands_sep'] : ',';
		$this->min = isset($this->params['min']) ? $this->params['min'] : '';
		$this->max = isset($this->params['max']) ? $this->params['max'] : '';
		$this->table_class = 'number';
		
		$this->attributes['rel'] = $this->thousands_sep.'|'.$this->dec_point.'|'.$this->min.'|'.$this->max;
		
		Event::add('wb_controller.pre_render_form', array($this, 'init_form'));
	}
	
	public function init_form()
	{
		Kohana::instance()->wb_template->js('plugins/number');
	}
	
	public function render_cell($value=null)
	{
		$value = $value===null ? $this->value : $value;
		return number_format($value, $this->decimals, $this->dec_point, $this->thousands_sep).$this->suffix;
	}
	
	public function prep_db()
	{
		$value = str_replace(array($this->thousands_sep, $this->dec_point), array('', '.'), $this->value);
		
		if ($this->min!='' && $value<$this->min) $value = $this->min;
		elseif ($this->max!='' && $value>$this->max) $value = $this->max;
		
		return 
			is_numeric($value) ? 
				($this->dec_point=='' ? (int)$value : (float)$value) :
				null;
	}
}

//End of Number_Plugin Library